package com.starblink.android.common.view.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 给 GridLayoutManager or StaggeredGridLayoutManager 设置间距，可设置去除首尾间距个数
 *
 * @author jingbin
 * https://github.com/youlookwhat/ByRecyclerView
 */

public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

    public static final int ORIENTATION_HORIZONTAL = 0;
    public static final int ORIENTATION_VERTICAL = 1;
    public static final int ORIENTATION_GRID = 2;

    private int orientation;
    private int leftSpace;
    private int topSpace;
    private int column;

    public static SpaceItemDecoration newHorizontalDecoration(int space) {
        return new SpaceItemDecoration(ORIENTATION_HORIZONTAL, space, 0, 0);
    }

    public static SpaceItemDecoration newVerticalDecoration(int space) {
        return new SpaceItemDecoration(ORIENTATION_VERTICAL, 0, space, 0);
    }

    public static SpaceItemDecoration newGridDecoration(int column, int leftSpace, int topSpace) {
        return new SpaceItemDecoration(ORIENTATION_GRID, leftSpace, topSpace, column);
    }

    public SpaceItemDecoration(int orientation, int leftSpace, int topSpace, int column) {
        this.orientation = orientation;
        this.leftSpace = leftSpace;
        this.topSpace = topSpace;
        this.column = column;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        outRect.left = leftSpace;
        outRect.top = topSpace;
        switch (orientation) {
            case ORIENTATION_HORIZONTAL:
                // 水平的LayoutManager，设置第一个item与左边界紧挨
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.left = 0;
                }
                break;
            case ORIENTATION_VERTICAL:
                // 垂直的LayoutManager，设置第一个item与上边界紧挨
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = 0;
                }
                break;
            case ORIENTATION_GRID:
                // 网格布局的LayoutManager，设置每一行的第一个item与左边界
                //紧挨，每一行最后一个item与右边界紧挨，其余自动向右侧偏移
                int mod = parent.getChildAdapterPosition(view) % column;
                outRect.left = leftSpace * mod;
                break;
        }
    }

}
